<template>
  <div class="call-detail">
    <div class="call-info">
      <div class="info-box">
        <span class="title">通话记录ID：</span
        ><span class="info">{{ cdrData._id }}</span>
      </div>
      <div class="info-box clearfix">
        <span class="fl info-text-left">
          <span class="title">号码：</span
          ><span class="info">{{
            cdrData.extraNumber
              ? cdrData.customerNumber + "-" + cdrData.extraNumber
              : cdrData.customerNumber | getHideTel
          }}</span>
        </span>
        <span class="fl">
          <span class="title">客户地区：</span
          ><span class="info">{{ cdrData | getProvince }}</span>
        </span>
      </div>
      <div class="info-box clearfix">
        <span class="fl info-text-left">
          <span class="title">呼叫类型：</span
          ><span class="info">{{ cdrData.callType | getCallType }}</span>
        </span>
        <span class="fl">
          <span class="title">呼叫状态：</span
          ><span class="info">{{ cdrData.status | getCallStatus }}</span>
        </span>
      </div>
      <div class="info-box clearfix">
        <span class="fl info-text-left">
          <span class="title">通话时长：</span
          ><span class="info">{{
            cdrData.bridgeDuration | getTimeLength
          }}</span>
        </span>
        <span class="fl">
          <span class="title">排队时长：</span
          ><span class="info">{{ cdrData.waitDuration | getTimeLength }}</span>
        </span>
      </div>
      <div class="info-box clearfix">
        <span class="fl info-text-left">
          <span class="title">满意度调查结果：</span
          ><span class="info">{{ cdrData.keysName }}</span>
        </span>
        <span class="fl">
          <span class="title">满意度调查时长：</span
          ><span class="info">{{
            cdrData.satisfyDuration | getTimeLength
          }}</span>
        </span>
      </div>

      <!--别删，迟早有一天会加回来的-->
      <!--<div class="info-box">-->
      <!--<span class="title">呼叫时间：</span><span class="info">{{ cdrData.startTime }}</span>-->
      <!--</div>-->
      <!--<div class="info-box">-->
      <!--<span class="title">语音导航：</span><span class="info">{{ cdrData.ivrName || '&#45;&#45;' }}</span>-->
      <!--</div>-->
      <!--<div class="info-box">-->
      <!--<span class="title">技能组：</span><span class="info">{{ cdrData.queueName || '&#45;&#45;' }}</span>-->
      <!--</div>-->
      <!--<div class="info-box">-->
      <!--<span class="title">呼叫座席时间：</span><span class="info">{{ cdrData.agentStartTime || '&#45;&#45;' }}</span>-->
      <!--</div>-->
      <!--<div class="info-box">-->
      <!--<span class="title">座席振铃时长：</span><span class="info">{{ cdrData.agentRingDuration | getTimeLength }}</span>-->
      <!--</div>-->
      <!--<div class="info-box">-->
      <!--<span class="title">座席接听时间：</span><span class="info">{{ cdrData.agentAnswerTime || '&#45;&#45;' }}</span>-->
      <!--</div>-->
      <!--<div class="info-box">-->
      <!--<span class="title">挂机时间：</span><span class="info">{{ cdrData.endTime }}</span>-->
      <!--</div>-->
      <div class="info-box clearfix">
        <span class="fl info-text-left">
          <span class="title">挂机方：</span
          ><span class="info">{{
            cdrData.hangUpSide | getHangUpSideName
          }}</span>
        </span>
      </div>
    </div>

    <div>
      <audioComponent
        v-if="
          renderComponent && (cdrData.recordFileUrl || cdrData.voiceMailUrl)
        "
        :flagId="'callDetail_' + cdrData._id"
        ref="audioRef"
        :isAutoPlay="false"
        :srcUrl="
          (cdrData.doubleTrackFileUrl ||
            cdrData.recordFileUrl ||
            cdrData.voiceMailUrl) | getFileUrl
        "
        :showDowload="showDowload"
        :showListen="showListen"
      ></audioComponent>
    </div>
    <!--<div class="ivr-list" v-show="cdrData.callType === 'incoming'">-->
    <div v-show="!hiddenLabels">
      <p class="tag">
        标签
        <span>
          <span
            @click="saveTags"
            v-if="functions.includes('callSheet_tag')"
            style="cursor: pointer"
            ><i class="V7_iconfont V7_iconV7tubiao_danxuan tip-span"></i
            >保存</span
          >
          <span
            class="middle"
            v-if="
              functions.includes('callSheet_tag') &&
              functions.includes('callSheet_tag_history')
            "
          ></span>
          <span
            @click="showDrawer"
            v-if="functions.includes('callSheet_tag_history')"
            style="cursor: pointer"
            ><i class="V7_iconfont tip-span V7_iconV7tubiao_chakanrizhi"></i
            >查看日志</span
          >
        </span>
      </p>
      <div class="tags">
        <tag
          v-for="(item, index) in tagList"
          :closeShow="functions.includes('callSheet_tag')"
          :key="'tag' + index"
          :data="item"
          @close="delTag"
        ></tag>
        <p style="margin: 10px 0; text-align: center" v-if="!tagList.length">
          暂无数据
        </p>
      </div>
      <div
        class="addTags"
        style="text-align: center; background: #fafafa"
        v-if="functions.includes('callSheet_tag')"
      >
        <p
          class="addTags-p"
          style="height: 32px"
          @click="addTagsShow = !addTagsShow"
        >
          <i class="el-icon-caret-bottom myicon"></i> <span>添加标签</span>
        </p>
        <el-cascader
          class="mycascader"
          v-if="addTagsShow"
          v-model="value"
          :options="options"
          filterable
          :props="cascaderProps"
        >
        </el-cascader>
        <!-- <el-button >保存</el-button> -->
      </div>

      <el-drawer
        title="标签日志"
        custom-class="m7-drawer my-drawer"
        size="480"
        :append-to-body="true"
        :visible.sync="innerDrawer"
      >
        <div class="labelLogs">
          <div
            class="labelLog"
            v-for="(item, index) in tagsHistoryList"
            :key="'log' + index"
          >
            <div class="decorate">
              <i class="V7_iconfont V7_iconV7tubiao_gengxin decorateicon"></i>
            </div>
            <div class="flex">
              <span>{{ item.updateTime }}</span>
              <span>{{ item.name }}</span>
            </div>
            <div class="stright"></div>
            <div>
              <span>更新</span>
              <span
                class="title"
                v-for="(q, i) in item.tagNames"
                :key="i + 'title'"
              >
                {{ q }}
              </span>
            </div>
          </div>
        </div>
      </el-drawer>
    </div>
    <div class="ivr-list">
      <div class="ivr-title">通话轨迹</div>
      <ivrList
        :id="cdrData._id"
        :showDowload="showDowload"
        :showListen="showListen"
      ></ivrList>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import audioComponent from '@components/audio/index.vue'
import ivrList from './tabCommon/ivrList.vue'
import tag from '@/components/tag/index.vue'
import { TagModule } from '@/store/modules/tag'
import { getCallTimeLength, getCallTypeName, getCallStatusName, commonAction, deepClone, checkHideTel } from '@/utils/common'
@Component({
  name: 'call-detail',
  components: { audioComponent, ivrList, tag },
  filters: {
    getHideTel (customerNumber) {
      return checkHideTel(customerNumber)
    },
    getFileUrl (url) {
      return url.replace(/(http|https):/ig, '')
    },
    getNodeName (type) {
      if (type === 'ivr-node-start') {
        return '开始节点'
      } else if (type === 'ivr-node-play') {
        return '播放语音节点'
      } else if (type === 'ivr-node-date') {
        return '时间条件节点'
      } else if (type === 'ivr-node-menu') {
        return '按键菜单节点'
      } else if (type === 'ivr-node-transfer') {
        return '转人工节点'
      } else if (type === 'ivr-node-callurl') {
        return '数据交互节点'
      } else if (type === 'ivr-node-collect') {
        return '采集收号节点'
      } else if (type === 'ivr-node-dynamic-route') {
        return '分支路由节点'
      }
    },
    getHangUpSideName (hangUpSide) {
      if (hangUpSide === 'AGENT') {
        return '座席挂机'
      } else if (hangUpSide === 'CUSTOMER') {
        return '客户挂机'
      } else if (hangUpSide === 'SYSTEM') {
        return '系统挂机'
      }
    },
    getTimeLength (timeLength) {
      return getCallTimeLength(timeLength, false)
    },
    getCallType (type) {
      return getCallTypeName(type)
    },
    getCallStatus (status) {
      return getCallStatusName(status)
    },
    getProvince (data) {
      let text = '未知';
      if (data.customerCountryCode === '86') {
        if (data.customerProvince) {
          text = data.customerProvince + '-' + data.customerCity
        }
      } else {
        if (data.customerCountry) {
          text = data.customerCountry
        }
      }
      return text;
    }
  }
})
export default class TabCalldetail extends Vue {
  @Prop({ default: {} }) private commonData!: any
  @Prop({ default: false }) private showDowload!: boolean
  @Prop({ default: false }) private showListen!: boolean
  @Prop({ default: false }) private hiddenLabels
  private $message
  private $getCache
  private cdrData: object = {}
  private cdrDataId: string = ''
  private renderComponent: boolean = true
  private $store: any
  private value = []
  private options = []
  private innerDrawer = false
  private addTagsShow = false
  private cascaderProps = {
    multiple: true,
    emitPath: false,
    checkStrictly: true,
    lazy: true,
    lazyLoad: (node, resolve) => {
      setTimeout(() => {
        resolve()
      }, 30)
    },
    value: '_id',
    label: 'name'
  }

  get getPhoneSatisfactionList () {
    return this.$store.state.common.publicCache.phoneSatisfactionList || []
  }

  @Watch('commonData', { immediate: true })
  private commonDataChange (newData) {
    // 先清除组件
    this.tagList = []
    this.addTagsShow = false
    this.renderComponent = false
    this.$nextTick(() => { // 波纹组件需要每次重载
      // 重新渲染组件
      this.renderComponent = true
      this.value = this.commonData.cdr?.tags || []
      if (this.commonData.cdr?.tags) {
        this.commonData.cdr.tags.forEach(element => {
          if (TagModule.tagMap.get(element)) {
            this.tagList.push(TagModule.tagMap.get(element))
          }
        })
      }
    })
    if (newData.cdr && newData.cdr.keys) {
      const satisArr = this.getPhoneSatisfactionList || []
      let str = ''
      satisArr.forEach((item1) => {
        if (newData.cdr.keys.indexOf(item1.key) > -1) {
          str += item1.value
        }
      })
      if (!str) {
        str = '--'
      }
      newData.cdr.keysName = str
    }
    this.cdrDataId = newData.cdr?._id
    this.$set(this, 'cdrData', newData.cdr || {})
  }

  private showDrawer () {
    this.getTagsHistory()
    this.innerDrawer = true
  }

  @Watch('$route')
  public closeDrawer () {
    this.innerDrawer = false
  }

  private tagList: any[] = []
  private created () {
    TagModule.getTagTree().then(res => {
      this.options = TagModule.tagTree
    })
  }

  get tagListMap () {
    const list: any = []
    if (this.commonData.cdr.tags) {
      this.commonData.cdr.tags.forEach(element => {
        list.push(TagModule.tagMap.get(element))
      })
    }
    return list
  }

  get functions () {
    return this.$store.state.common.session.user.functions || []
  }

  private saveTags () {
    const list = deepClone(this.value)
    const arr: any[] = []
    list.forEach(i => {
      arr.push({ _id: i, name: TagModule.tagMap.get(i)?.fullName, color: TagModule.tagMap.get(i)?.color || '#ccc' })
    })
    const data = {
      cdrId: this.commonData.callSheetId,
      tags: arr
    }
    commonAction({ url: '/call/action/cdr/tag', method: 'post', data }).then(res => {
      if (res.success) {
        this.$message.success('添加成功')
        this.tagList = arr;
        (this as any).$bus.$emit('changeTagData', this.value, this.commonData.callSheetId)
      }
    })
  }

  private delTag (id) {
    const list = deepClone(this.tagList)
    const arr = deepClone(this.value)
    arr.splice(arr.findIndex(i => i === id), 1)
    list.splice(list.findIndex(i => i._id === id), 1)
    const data = {
      cdrId: this.commonData.callSheetId,
      tags: list
    }
    commonAction({ url: '/call/action/cdr/tag', method: 'post', data }).then(res => {
      if (res.success) {
        this.$message.success('删除成功')
        this.tagList = list
        this.$set(this, 'value', arr);
        (this as any).$bus.$emit('changeTagData', this.value, this.commonData.callSheetId)
      }
    })
  }

  private tagsHistoryList: any = []
  private getTagsHistory () {
    commonAction({ url: '/call/action/cdr/tagHistory/query', method: 'post', data: { cdrId: this.commonData.callSheetId } }).then(res => {
      if (res.success && res.data.count > 0) {
        this.tagsHistoryList = res.data.list.map(i => {
          const user = this.$store.state.common.publicCache.userListObj[i.updateUser]
          i.name = user.name
          return i
        })
      } else {
        this.tagsHistoryList = []
      }
    })
  }

  private mounted () {
    this.$getCache('/call/action/general/query', ['phoneSatisfactionList'], false)
  }
}
</script>

<style lang="stylus" scoped>
.call-detail
  height 100%
  overflow auto
  font-size 12px
  .info-box
    margin-bottom 15px
    .info-text-left
      width 40%
  .title
    color $fc-gray2
  .info
    color $fc-gray3
  .ivr-title
    font-weight 600
    margin-bottom 20px
    font-size 14px
  .ivr-tab
    border-top 1px solid #E7E9ED
  .ivr-list
    padding-top 15px
  .ivr-time
    margin-right 15px
  >>> .el-timeline-item__node--large
    left 2px
    width 6px
    height 6px
  >>> .el-timeline-item__wrapper
    top -3px
  >>> .el-timeline-item__content
    color $fc-gray3
    font-size 12px
  >>> .el-timeline-item__tail
    border-left 2px solid #AFDCFC
.tag
  height 14px
  font-size 14px
  font-family PingFang SC
  font-weight 600
  color #303753
  line-height 14px
  margin-bottom 20px
  span
    float right
    color #008BEE
.tags
  background #FFFFFF
  border 1px solid #E7E9ED
  border-radius 4px 4px 0 0
  padding 12px
.addTags
  border 1px solid #E7E9ED
  border-top none
.tip-span
  font-size 14px
  margin-right 5px
  color #008BEE
.middle
  height 10px
  line-height 14px
  width 1px
  background #008BEE
  margin 2px 10px
  display inline-block
.labelLogs
  width 100%
  height 100%
  padding 24px
  min-width 480px
  position relative
  .labelLog
    background #FFFFFF
    border 1px solid #ECF0F3
    border-radius 4px
    min-height 88px
    padding 14px 40px
    width 432px
    margin-bottom 25px
    position relative
    .stright
      height 1px
      background #ECF0F3
      border-radius 1px
      width 100%
      margin-top 13px
      margin-bottom 13px
    .flex
      display flex
      justify-content space-between
    .title
      margin 0 5px
      background #FAFAFA
      border 1px solid #E7E9ED
      border-radius 4px
      display inline-block
      padding 6px 8px
      margin-bottom 5px
.addTags-p
  line-height 32px
  cursor pointer
  i
    color #A6A6AE
  &:hover
    color #008BEE
    i
      color #008BEE
    span
      display inline-block
.mycascader
  margin 10px 0px
  width 90%
/deep/.my-drawer .el-drawer__body
  overflow auto
.decorate
  position absolute
  background #008BEE
  display flex
  align-items center
  justify-content center
  width 20px
  height 20px
  border-radius 10px
  background #008BEE
  box-shadow 0px 1px 6px 0px rgba(98,172,224,0.56)
  top -10px
  left 10px
.decorateicon
  color #fff
</style>
